package com.roamer.rest.common;

import org.springframework.util.Assert;

import java.util.Optional;

/**
 * 登陆用户存储
 *
 * @author roamer
 * @version V1.0
 * @date 2019-07-22 11:36
 */
public class UserContextHolder {

    private static final ThreadLocal<UserContext> USER_CONTEXT = new ThreadLocal<>();

    public static UserContext getUserContext() {
        return Optional.ofNullable(USER_CONTEXT.get()).orElseGet(() -> {
            UserContext context = createEmptyContext();
            USER_CONTEXT.set(context);
            return context;
        });

    }

    public static void setContext(UserContext context) {
        Assert.notNull(context, "Only non-null UserContext instances are permitted");
        USER_CONTEXT.set(context);
    }

    public static void clean() {
        USER_CONTEXT.remove();
    }

    private static UserContext createEmptyContext() {
        return new UserContext();
    }

}
